package proxy.dynamicStatic;

import proxy.proxyStatic.Function;
import proxy.proxyStatic.IFunction;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Lenovo
 */
public class ProxyFactory {
    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    /**
     * 给目标对象生成代理对象
     *
     * @return
     */
    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                //指定当前target对象使用类加载器
                target.getClass().getClassLoader(),
                //target对象实现的接口的类型
                target.getClass().getInterfaces(),
                //事件处理
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("dynamic pre.." + method.getName());
                        Object returnValue = method.invoke(target, args);
                        System.out.println("dynamic after.." + method.getName());
                        return returnValue;
                    }
                }
        );
    }

    public static void main(String[] args) {
        // 目标对象
        IFunction target = new Function();

        IFunction proxy = (IFunction) new ProxyFactory(target).getProxyInstance();
        System.out.println(proxy.getClass());
        proxy.fun();
    }

}
